Ext.define('DragonApp.view.broadcast.Controller', {
    extend: 'DragonApp.view.foundation.ViewController',

    alias: 'controller.broadcast',

    config: {
        severlist: Ext.create('DragonApp.store.JsonPServer', {})
    },

    //创建窗体
    createDialog: function(record) {

        var me = this,
            view = me.getView();

        me.dialog = view.add({
            xtype: 'broadcast_window',
            height: 400,
            width: 800,
            viewModel: {
                data: {
                    title: record ? '编辑' : '新增'
                }
            }
        });
        //========
        //表单类型
        //========
        var typeField = Ext.ComponentQuery.query('hiddenfield#formtype')[0];
        var serverField = Ext.ComponentQuery.query('broadcast_window multiservercombo')[0];

        if (!Ext.isEmpty(record)) {

            //表单赋值
            me.dialog.down("form").loadRecord(record);

            //只读约束
            serverField.setReadOnly(true);
            serverField.on('beforequery', function() {
                return false;
            });

            //表单类型
            typeField.setValue('edit');

        } else {
            typeField.setValue('new');
        }
        me.dialog.show();
    },

    //单记录删除
    onDelete: function(button, e, options) {

        //当前记录
        var record = button.getWidgetRecord();
        var param = { id: record.get('id') };
        var url = DragonApp.ux.config.Config.getUrl('/index/Broadcast/delete/');

        //删除请求
        this.deletePrompt(url, param, record);

    },

    //批量删除
    onBatDelete: function() {

        var grid = this.getView();
        var url = DragonApp.ux.config.Config.getUrl('/index/Broadcast/batDelete/');

        this.onBatDeleteExec(grid,url);
    },
    //==========
    //工具栏搜索
    //==========
    onSearch: function() {

        //搜索字段
        var searchFilter = Ext.ComponentQuery.query('broadcast-bar')[0];
        var searchField = searchFilter.queryById('search_field');

        //复位
        var store = Ext.data.StoreManager.lookup('jsonPBroadcastStore');
        store.clearFilter();

        //内容过滤
        store.filterBy(function(item) {

            return (item.get('content').indexOf(searchField.getValue()) >= 0);
        });
    },

    //========
    //查询搜索
    //========
    onSubmitClick: function(button, e, options) {

        var me = this;
        var form = this.getView().getForm();

        if (!form.isValid()) return;

        var formValue = form.getValues();

        //搜索字段
        var serverComboboxValue = formValue.sid;

        //复位
        var store = Ext.data.StoreManager.lookup('jsonPBroadcastStore');
        store.clearFilter();

        //内容过滤
        store.filterBy(function(item) {
            return (item.get('server').indexOf(serverComboboxValue) >= 0);
        });
    },

    //回车搜索
    onTextFieldSpecialKeySearch: function(field, e, options) {
        if (e.getKey() === e.ENTER) {
            this.onSearch();
        }
    },

    //新增、编辑提交
    onSave: function(button, e, options) {

        var window = button.up('window');
        var form = window.down('form').getForm();

        if (!form.isValid()) return;

        var formValue = form.getValues();
        formValue.server = formValue.server.toString();

        //配置(表单类型)提交网址
        var url = ('new' == formValue.type) ? '/index/Broadcast/add/' : '/index/Broadcast/update/';
        url = DragonApp.ux.config.Config.getUrl(url);

        var grid = Ext.ComponentQuery.query('broadcastgrid')[0];
        var store = grid.getStore();

        window.mask('提交中...');

        //数据仓库根据查询附加参数加载

        Ext.data.JsonP.request({
            url: url,
            async: false,
            params: formValue,
            callbackKey: "callback",
            success: function(result) {

                window.unmask();
                DragonApp.util.Msg.showToast(result.msg);

                switch (result.success) {
                    case true:
                        form.destroy();
                        window.destroy();
                        store.load();
                        break;
                }
            },
            failure: function(result) {
                window.unmask();
                DragonApp.util.Msg.showToast(result);
            }
        });
    },

    //========
    //回车响应
    //========
    onTextFieldSpecialKey: function(field, e, options) {
        if (e.getKey() === e.ENTER) {
            if (this.getView().getForm().isValid()) {
                this.onSubmitClick();
            }
        }
    },

    //============
    //状态提示渲染
    //============
    statusRender: function(value, metadata, record, rowIndex, columnIndex, store) {
        var begintime = Date.parse(record.get("start_time"));
        var endtime = Date.parse(record.get("end_time"));
        var nowtime = Date.parse(new Date());
        if (nowtime >= begintime && nowtime <= endtime) {
            return '有效';
        } else {
            return '失效';
        }
    },

    //===========
    //服务器渲染
    //===========
    serverRender: function(value) {
        var store = this.getSeverlist();

        //遍历store中的记录
        for (var i = 0; i < store.getCount(); i++) {
            //获取第i条记录
            var record = store.getAt(i);
            if (value == record.get('id')) {
                return record.get('hostname');
            }
        }
        return value;
    },

    //============
    //内容提示渲染
    //============
    attrRender: function(value, metadata, record, rowIndex, columnIndex, store) {

        if (typeof(value) == "undefined") {
            value = '';
            metadata.tdAttr = 'data-qtip="' + value + '" ' + 'data-qalign="bl-br"' + 'data-qwidth="auto"';
            return value;
        } else {
            metadata.tdAttr = 'data-qtip="' + value + '" ' + 'data-qalign="bl-br"' + 'data-qwidth="auto"';
            return value;
        }
    }
});